4 * Blocks and bans object
9 * All the functions in this class assume the object is either explicitly
10 * loaded or filled. It is not load-on-demand. There are no accessors.
12 * Globals used: $wgAutoblockExpiry, $wgAntiLockFlags
14 * @todo This could be used everywhere, but it isn't.
18 /* public*/ var $mAddress, $mUser, $mBy, $mReason, $mTimestamp, $mAuto, $mId, $mExpiry,
19 $mRangeStart, $mRangeEnd, $mAnonOnly, $mEnableAutoblock, $mHideName,
20 $mBlockEmail, $mByName, $mAngryAutoblock;
21 /* private */ var $mNetworkBits, $mIntegerAddr, $mForUpdate, $mFromMaster;
23 const EB_KEEP_EXPIRED
= 1;
24 const EB_FOR_UPDATE
= 2;
25 const EB_RANGE_ONLY
= 4;
27 function __construct( $address = '', $user = 0, $by = 0, $reason = '',
28 $timestamp = '' , $auto = 0, $expiry = '', $anonOnly = 0, $createAccount = 0, $enableAutoblock = 0,
29 $hideName = 0, $blockEmail = 0 )
32 # Expand valid IPv6 addresses
33 $address = IP
::sanitizeIP( $address );
34 $this->mAddress
= $address;
37 $this->mReason
= $reason;
38 $this->mTimestamp
= wfTimestamp(TS_MW
,$timestamp);
40 $this->mAnonOnly
= $anonOnly;
41 $this->mCreateAccount
= $createAccount;
42 $this->mExpiry
= self
::decodeExpiry( $expiry );
43 $this->mEnableAutoblock
= $enableAutoblock;
44 $this->mHideName
= $hideName;
45 $this->mBlockEmail
= $blockEmail;
46 $this->mForUpdate
= false;
47 $this->mFromMaster
= false;
48 $this->mByName
= false;
49 $this->mAngryAutoblock
= false;
50 $this->initialiseRange();
54 * Load a block from the database, using either the IP address or
57 * @return Block Object
58 * @param $address string IP address of user/anon
59 * @param $user int User id of user
60 * @param $killExpired bool Delete expired blocks on load
62 static function newFromDB( $address, $user = 0, $killExpired = true )
65 $block->load( $address, $user, $killExpired );
66 if ( $block->isValid() ) {
74 * Load a blocked user from their block id.
75 * @return Block object
76 * @param $id int Block id to search for
78 static function newFromID( $id )
80 $dbr = wfGetDB( DB_SLAVE
);
81 $res = $dbr->resultObject( $dbr->select( 'ipblocks', '*',
82 array( 'ipb_id' => $id ), __METHOD__
) );
84 if ( $block->loadFromResult( $res ) ) {
92 * Clear all member variables in the current object. Does not clear
93 * the block from the DB.
97 $this->mAddress
= $this->mReason
= $this->mTimestamp
= '';
98 $this->mId
= $this->mAnonOnly
= $this->mCreateAccount
=
99 $this->mEnableAutoblock
= $this->mAuto
= $this->mUser
=
100 $this->mBy
= $this->mHideName
= $this->mBlockEmail
= 0;
101 $this->mByName
= false;
105 * Get the DB object and set the reference parameter to the query options
108 function &getDBOptions( &$options ) {
109 global $wgAntiLockFlags;
110 if ( $this->mForUpdate ||
$this->mFromMaster
) {
111 $db = wfGetDB( DB_MASTER
);
112 if ( !$this->mForUpdate ||
($wgAntiLockFlags & ALF_NO_BLOCK_LOCK
) ) {
115 $options = array( 'FOR UPDATE' );
118 $db = wfGetDB( DB_SLAVE
);
125 * Get a ban from the DB, with either the given address or the given username
127 * @param $address string The IP address of the user, or blank to skip IP blocks
128 * @param $user int The user ID, or zero for anonymous users
129 * @param $killExpired bool Whether to delete expired rows while loading
132 function load( $address = '', $user = 0, $killExpired = true )
134 wfDebug( "Block::load: '$address', '$user', $killExpired\n" );
137 $db =& $this->getDBOptions( $options );
139 if ( 0 == $user && $address == '' ) {
140 # Invalid user specification, not blocked
147 $res = $db->resultObject( $db->select( 'ipblocks', '*', array( 'ipb_user' => $user ),
148 __METHOD__
, $options ) );
149 if ( $this->loadFromResult( $res, $killExpired ) ) {
155 # TODO: improve performance by merging this query with the autoblock one
156 # Slightly tricky while handling killExpired as well
158 $conds = array( 'ipb_address' => $address, 'ipb_auto' => 0 );
159 $res = $db->resultObject( $db->select( 'ipblocks', '*', $conds, __METHOD__
, $options ) );
160 if ( $this->loadFromResult( $res, $killExpired ) ) {
161 if ( $user && $this->mAnonOnly
) {
162 # Block is marked anon-only
163 # Whitelist this IP address against autoblocks and range blocks
173 if ( $this->loadRange( $address, $killExpired, $user ) ) {
174 if ( $user && $this->mAnonOnly
) {
184 $conds = array( 'ipb_address' => $address, 'ipb_auto' => 1 );
186 $conds['ipb_anon_only'] = 0;
188 $res = $db->resultObject( $db->select( 'ipblocks', '*', $conds, __METHOD__
, $options ) );
189 if ( $this->loadFromResult( $res, $killExpired ) ) {
200 * Fill in member variables from a result wrapper
202 * @param $res ResultWrapper Row from the ipblocks table
203 * @param $killExpired bool Whether to delete expired rows while loading
205 function loadFromResult( ResultWrapper
$res, $killExpired = true )
208 if ( 0 != $res->numRows() ) {
210 $row = $res->fetchObject();
211 $this->initFromRow( $row );
213 if ( $killExpired ) {
214 # If requested, delete expired rows
216 $killed = $this->deleteIfExpired();
218 $row = $res->fetchObject();
220 $this->initFromRow( $row );
223 } while ( $killed && $row );
225 # If there were any left after the killing finished, return true
238 * Search the database for any range blocks matching the given address, and
239 * load the row if one is found.
241 * @param $address string IP address range
242 * @param $killExpired bool Whether to delete expired rows while loading
243 * @param $userid int If not 0, then sets ipb_anon_only
245 function loadRange( $address, $killExpired = true, $user = 0 )
247 $iaddr = IP
::toHex( $address );
248 if ( $iaddr === false ) {
253 # Only scan ranges which start in this /16, this improves search speed
254 # Blocks should not cross a /16 boundary.
255 $range = substr( $iaddr, 0, 4 );
258 $db =& $this->getDBOptions( $options );
260 "ipb_range_start LIKE '$range%'",
261 "ipb_range_start <= '$iaddr'",
262 "ipb_range_end >= '$iaddr'"
266 $conds['ipb_anon_only'] = 0;
269 $res = $db->resultObject( $db->select( 'ipblocks', '*', $conds, __METHOD__
, $options ) );
270 $success = $this->loadFromResult( $res, $killExpired );
275 * Determine if a given integer IPv4 address is in a given CIDR network
276 * @deprecated Use IP::isInRange
278 function isAddressInRange( $addr, $range ) {
279 return IP
::isInRange( $addr, $range );
283 * Given a database row from the ipblocks table, initialize
285 * @param $row ResultWrapper A row from the ipblocks table
287 function initFromRow( $row )
289 $this->mAddress
= $row->ipb_address
;
290 $this->mReason
= $row->ipb_reason
;
291 $this->mTimestamp
= wfTimestamp(TS_MW
,$row->ipb_timestamp
);
292 $this->mUser
= $row->ipb_user
;
293 $this->mBy
= $row->ipb_by
;
294 $this->mAuto
= $row->ipb_auto
;
295 $this->mAnonOnly
= $row->ipb_anon_only
;
296 $this->mCreateAccount
= $row->ipb_create_account
;
297 $this->mEnableAutoblock
= $row->ipb_enable_autoblock
;
298 $this->mBlockEmail
= $row->ipb_block_email
;
299 $this->mHideName
= $row->ipb_deleted
;
300 $this->mId
= $row->ipb_id
;
301 $this->mExpiry
= self
::decodeExpiry( $row->ipb_expiry
);
302 if ( isset( $row->user_name
) ) {
303 $this->mByName
= $row->user_name
;
305 $this->mByName
= $row->ipb_by_text
;
307 $this->mRangeStart
= $row->ipb_range_start
;
308 $this->mRangeEnd
= $row->ipb_range_end
;
312 * Once $mAddress has been set, get the range they came from.
313 * Wrapper for IP::parseRange
315 function initialiseRange()
317 $this->mRangeStart
= '';
318 $this->mRangeEnd
= '';
320 if ( $this->mUser
== 0 ) {
321 list( $this->mRangeStart
, $this->mRangeEnd
) = IP
::parseRange( $this->mAddress
);
326 * Callback with a Block object for every block
327 * @return integer number of blocks;
329 /*static*/ function enumBlocks( $callback, $tag, $flags = 0 )
331 global $wgAntiLockFlags;
333 $block = new Block();
334 if ( $flags & Block
::EB_FOR_UPDATE
) {
335 $db = wfGetDB( DB_MASTER
);
336 if ( $wgAntiLockFlags & ALF_NO_BLOCK_LOCK
) {
339 $options = 'FOR UPDATE';
341 $block->forUpdate( true );
343 $db = wfGetDB( DB_SLAVE
);
346 if ( $flags & Block
::EB_RANGE_ONLY
) {
347 $cond = " AND ipb_range_start <> ''";
352 $now = wfTimestampNow();
354 list( $ipblocks, $user ) = $db->tableNamesN( 'ipblocks', 'user' );
356 $sql = "SELECT $ipblocks.*,user_name FROM $ipblocks,$user " .
357 "WHERE user_id=ipb_by $cond ORDER BY ipb_timestamp DESC $options";
358 $res = $db->query( $sql, 'Block::enumBlocks' );
359 $num_rows = $db->numRows( $res );
361 while ( $row = $db->fetchObject( $res ) ) {
362 $block->initFromRow( $row );
363 if ( ( $flags & Block
::EB_RANGE_ONLY
) && $block->mRangeStart
== '' ) {
367 if ( !( $flags & Block
::EB_KEEP_EXPIRED
) ) {
368 if ( $block->mExpiry
&& $now > $block->mExpiry
) {
371 call_user_func( $callback, $block, $tag );
374 call_user_func( $callback, $block, $tag );
377 $db->freeResult( $res );
382 * Delete the row from the IP blocks table.
391 throw new MWException( "Block::delete() now requires that the mId member be filled\n" );
394 $dbw = wfGetDB( DB_MASTER
);
395 $dbw->delete( 'ipblocks', array( 'ipb_id' => $this->mId
), __METHOD__
);
396 return $dbw->affectedRows() > 0;
400 * Insert a block into the block table.
401 * @return bool Whether or not the insertion was successful.
405 wfDebug( "Block::insert; timestamp {$this->mTimestamp}\n" );
406 $dbw = wfGetDB( DB_MASTER
);
408 # Unset ipb_anon_only for user blocks, makes no sense
409 if ( $this->mUser
) {
410 $this->mAnonOnly
= 0;
413 # Unset ipb_enable_autoblock for IP blocks, makes no sense
414 if ( !$this->mUser
) {
415 $this->mEnableAutoblock
= 0;
416 $this->mBlockEmail
= 0; //Same goes for email...
419 if( !$this->mByName
) {
421 $this->mByName
= User
::whoIs( $this->mBy
);
424 $this->mByName
= $wgUser->getName();
428 # Don't collide with expired blocks
429 Block
::purgeExpired();
431 $ipb_id = $dbw->nextSequenceValue('ipblocks_ipb_id_val');
432 $dbw->insert( 'ipblocks',
435 'ipb_address' => $this->mAddress
,
436 'ipb_user' => $this->mUser
,
437 'ipb_by' => $this->mBy
,
438 'ipb_by_text' => $this->mByName
,
439 'ipb_reason' => $this->mReason
,
440 'ipb_timestamp' => $dbw->timestamp($this->mTimestamp
),
441 'ipb_auto' => $this->mAuto
,
442 'ipb_anon_only' => $this->mAnonOnly
,
443 'ipb_create_account' => $this->mCreateAccount
,
444 'ipb_enable_autoblock' => $this->mEnableAutoblock
,
445 'ipb_expiry' => self
::encodeExpiry( $this->mExpiry
, $dbw ),
446 'ipb_range_start' => $this->mRangeStart
,
447 'ipb_range_end' => $this->mRangeEnd
,
448 'ipb_deleted' => $this->mHideName
,
449 'ipb_block_email' => $this->mBlockEmail
450 ), 'Block::insert', array( 'IGNORE' )
452 $affected = $dbw->affectedRows();
455 $this->doRetroactiveAutoblock();
461 * Retroactively autoblocks the last IP used by the user (if it is a user)
462 * blocked by this Block.
463 * @return bool Whether or not a retroactive autoblock was made.
465 function doRetroactiveAutoblock() {
466 $dbr = wfGetDB( DB_SLAVE
);
467 #If autoblock is enabled, autoblock the LAST IP used
468 # - stolen shamelessly from CheckUser_body.php
470 if ($this->mEnableAutoblock
&& $this->mUser
) {
471 wfDebug("Doing retroactive autoblocks for " . $this->mAddress
. "\n");
473 $options = array( 'ORDER BY' => 'rc_timestamp DESC' );
474 $conds = array( 'rc_user_text' => $this->mAddress
);
476 if ($this->mAngryAutoblock
) {
477 // Block any IP used in the last 7 days. Up to five IPs.
478 $conds[] = 'rc_timestamp < ' . $dbr->addQuotes( $dbr->timestamp( time() - (7*86400) ) );
479 $options['LIMIT'] = 5;
481 // Just the last IP used.
482 $options['LIMIT'] = 1;
485 $res = $dbr->select( 'recentchanges', array( 'rc_ip' ), $conds,
486 __METHOD__
, $options);
488 if ( !$dbr->numRows( $res ) ) {
489 #No results, don't autoblock anything
490 wfDebug("No IP found to retroactively autoblock\n");
492 while ( $row = $dbr->fetchObject( $res ) ) {
494 $this->doAutoblock( $row->rc_ip
);
501 * Checks whether a given IP is on the autoblock whitelist.
503 * @param string $autoblockip The IP to check
505 function isWhitelistedFromAutoblocks( $ip ) {
508 // Try to get the autoblock_whitelist from the cache, as it's faster
509 // than getting the msg raw and explode()'ing it.
510 $key = wfMemc( 'ipb', 'autoblock', 'whitelist' );
511 $lines = $wgMemc->get( $key );
513 $lines = explode( "\n", wfMsgForContentNoTrans( 'autoblock_whitelist' ) );
516 wfDebug("Checking the autoblock whitelist..\n");
518 foreach( $lines as $line ) {
520 if ( substr( $line, 0, 1 ) !== '*' ) {
524 $wlEntry = substr($line, 1);
525 $wlEntry = trim($wlEntry);
527 wfDebug("Checking $ip against $wlEntry...");
529 # Is the IP in this range?
530 if (IP
::isInRange( $ip, $wlEntry )) {
531 wfDebug(" IP $ip matches $wlEntry, not autoblocking\n");
534 wfDebug( " No match\n" );
542 * Autoblocks the given IP, referring to this Block.
543 * @param string $autoblockip The IP to autoblock.
544 * @param bool $justInserted The main block was just inserted
545 * @return bool Whether or not an autoblock was inserted.
547 function doAutoblock( $autoblockip, $justInserted = false ) {
548 # If autoblocks are disabled, go away.
549 if ( !$this->mEnableAutoblock
) {
553 # Check for presence on the autoblock whitelist
554 if (Block
::isWhitelistedFromAutoblocks($autoblockip)) {
558 ## Allow hooks to cancel the autoblock.
559 if (!wfRunHooks( 'AbortAutoblock', array( $autoblockip, &$this ) )) {
560 wfDebug( "Autoblock aborted by hook." );
564 # It's okay to autoblock. Go ahead and create/insert the block.
566 $ipblock = Block
::newFromDB( $autoblockip );
568 # If the user is already blocked. Then check if the autoblock would
569 # exceed the user block. If it would exceed, then do nothing, else
571 if ($this->mExpiry
&&
572 ($this->mExpiry
< Block
::getAutoblockExpiry($ipblock->mTimestamp
))) {
575 # Just update the timestamp
576 if ( !$justInserted ) {
577 $ipblock->updateTimestamp();
581 $ipblock = new Block
;
584 # Make a new block object with the desired properties
585 wfDebug( "Autoblocking {$this->mAddress}@" . $autoblockip . "\n" );
586 $ipblock->mAddress
= $autoblockip;
588 $ipblock->mBy
= $this->mBy
;
589 $ipblock->mByName
= $this->mByName
;
590 $ipblock->mReason
= wfMsgForContent( 'autoblocker', $this->mAddress
, $this->mReason
);
591 $ipblock->mTimestamp
= wfTimestampNow();
593 $ipblock->mCreateAccount
= $this->mCreateAccount
;
594 # Continue suppressing the name if needed
595 $ipblock->mHideName
= $this->mHideName
;
597 # If the user is already blocked with an expiry date, we don't
598 # want to pile on top of that!
600 $ipblock->mExpiry
= min ( $this->mExpiry
, Block
::getAutoblockExpiry( $this->mTimestamp
));
602 $ipblock->mExpiry
= Block
::getAutoblockExpiry( $this->mTimestamp
);
605 return $ipblock->insert();
609 * Check if a block has expired. Delete it if it is.
612 function deleteIfExpired()
614 $fname = 'Block::deleteIfExpired';
615 wfProfileIn( $fname );
616 if ( $this->isExpired() ) {
617 wfDebug( "Block::deleteIfExpired() -- deleting\n" );
621 wfDebug( "Block::deleteIfExpired() -- not expired\n" );
624 wfProfileOut( $fname );
629 * Has the block expired?
634 wfDebug( "Block::isExpired() checking current " . wfTimestampNow() . " vs $this->mExpiry\n" );
635 if ( !$this->mExpiry
) {
638 return wfTimestampNow() > $this->mExpiry
;
643 * Is the block address valid (i.e. not a null string?)
648 return $this->mAddress
!= '';
652 * Update the timestamp on autoblocks.
654 function updateTimestamp()
656 if ( $this->mAuto
) {
657 $this->mTimestamp
= wfTimestamp();
658 $this->mExpiry
= Block
::getAutoblockExpiry( $this->mTimestamp
);
660 $dbw = wfGetDB( DB_MASTER
);
661 $dbw->update( 'ipblocks',
663 'ipb_timestamp' => $dbw->timestamp($this->mTimestamp
),
664 'ipb_expiry' => $dbw->timestamp($this->mExpiry
),
665 ), array( /* WHERE */
666 'ipb_address' => $this->mAddress
667 ), 'Block::updateTimestamp'
673 function getIntegerAddr()
675 return $this->mIntegerAddr;
678 function getNetworkBits()
680 return $this->mNetworkBits;
684 * Get the user id of the blocking sysop
687 public function getBy() {
692 * Get the username of the blocking sysop
697 return $this->mByName
;
700 function forUpdate( $x = NULL ) {
701 return wfSetVar( $this->mForUpdate
, $x );
704 function fromMaster( $x = NULL ) {
705 return wfSetVar( $this->mFromMaster
, $x );
708 function getRedactedName() {
709 if ( $this->mAuto
) {
710 return '#' . $this->mId
;
712 return $this->mAddress
;
717 * Encode expiry for DB
719 * @param $expiry string Timestamp for expiry, or
720 * @param $db Database object
722 static function encodeExpiry( $expiry, $db ) {
723 if ( $expiry == '' ||
$expiry == Block
::infinity() ) {
724 return Block
::infinity();
726 return $db->timestamp( $expiry );
731 * Decode expiry which has come from the DB
733 * @param $expiry string Database expiry format
734 * @param $timestampType Requested timestamp format
736 static function decodeExpiry( $expiry, $timestampType = TS_MW
) {
737 if ( $expiry == '' ||
$expiry == Block
::infinity() ) {
738 return Block
::infinity();
740 return wfTimestamp( $timestampType, $expiry );
745 * Get a timestamp of the expiry for autoblocks
748 static function getAutoblockExpiry( $timestamp )
750 global $wgAutoblockExpiry;
751 return wfTimestamp( TS_MW
, wfTimestamp( TS_UNIX
, $timestamp ) +
$wgAutoblockExpiry );
755 * Gets rid of uneeded numbers in quad-dotted/octet IP strings
756 * For example, 127.111.113.151/24 -> 127.111.113.0/24
757 * @param $range string IP address to normalize
760 static function normaliseRange( $range ) {
761 $parts = explode( '/', $range );
762 if ( count( $parts ) == 2 ) {
764 if ( IP
::isIPv6($range) && $parts[1] >= 64 && $parts[1] <= 128 ) {
766 $ipint = IP
::toUnsigned6( $parts[0] );
767 # Native 32 bit functions WONT work here!!!
768 # Convert to a padded binary number
769 $network = wfBaseConvert( $ipint, 10, 2, 128 );
770 # Truncate the last (128-$bits) bits and replace them with zeros
771 $network = str_pad( substr( $network, 0, $bits ), 128, 0, STR_PAD_RIGHT
);
772 # Convert back to an integer
773 $network = wfBaseConvert( $network, 2, 10 );
774 # Reform octet address
775 $newip = IP
::toOctet( $network );
776 $range = "$newip/{$parts[1]}";
778 else if ( IP
::isIPv4($range) && $parts[1] >= 16 && $parts[1] <= 32 ) {
779 $shift = 32 - $parts[1];
780 $ipint = IP
::toUnsigned( $parts[0] );
781 $ipint = $ipint >> $shift << $shift;
782 $newip = long2ip( $ipint );
783 $range = "$newip/{$parts[1]}";
790 * Purge expired blocks from the ipblocks table
792 static function purgeExpired() {
793 $dbw = wfGetDB( DB_MASTER
);
794 $dbw->delete( 'ipblocks', array( 'ipb_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ), __METHOD__
);
798 * This is a special keyword for timestamps in PostgreSQL, and
799 * works with CHAR(14) as well because "i" sorts after all numbers.
802 static function infinity() {
807 * Convert a DB-encoded expiry into a real string that humans can read.
810 * @todo @fixme This is nasty. Forces a msg on the expiry, which isn't what
811 * we want. Probably want to abstract out the number formatting so it can
812 * be used elsewhere (some bug I forgot and can't find at the moment)
814 static function formatExpiry( $encoded_expiry ) {
818 if( is_null( $msg ) ) {
820 $keys = array( 'infiniteblock', 'expiringblock' );
821 foreach( $keys as $key ) {
822 $msg[$key] = wfMsgHtml( $key );
826 $expiry = Block
::decodeExpiry( $encoded_expiry );
827 if ($expiry == 'infinity') {
828 $expirystr = $msg['infiniteblock'];
831 $expiretimestr = $wgLang->timeanddate( $expiry, true );
832 $expirystr = wfMsgReplaceArgs( $msg['expiringblock'], array($expiretimestr) );
839 * Convert a typed-in expiry time into something we can put into the database.
840 * @param $expiry_input string Whatever was typed into the form
841 * @return string More database friendly
843 static function parseExpiryInput( $expiry_input ) {
844 if ( $expiry_input == 'infinite' ||
$expiry_input == 'indefinite' ) {
845 $expiry = 'infinity';
847 $expiry = strtotime( $expiry_input );
848 if ($expiry < 0 ||
$expiry === false) {